package filter;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.User;

/**
 * <li>核心登录业务控制
 */
//@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 获取参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 硬判断，写死了用户名和密码，思考真实的业务场境，如何取用户名和密码判断？
		if ("fhzheng".equals(username) && "123546".equals(password)) {
			// 通过了检测，则封装数据
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			request.getSession().setAttribute("user", user);
			
			//发送自动登录的cookie，为以后的自动登录做准备
			String autoLogin = request.getParameter("autologin");
			if (autoLogin !=null) {
				// 封装用户名和密码，然后丢到cookie的某个键值中
				Cookie cookie = new Cookie("autologin", username+"-"+password);
				// 设置cookie的有效时间
				cookie.setMaxAge(Integer.parseInt(autoLogin));
				// 设置路径
				cookie.setPath(request.getContextPath());
				// 添加cookie
				response.addCookie(cookie);
			}
			
			//Servlet的核心业务完成：通过登录校验，控制跳转到首页
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		} else {
			//Servlet的核心业务完成：未通过登录校验，控制跳转回到登录页，并给出出错信息提示
			request.setAttribute("errorMsg", "用户名或密码错误");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
